const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const e = require('express');

const app = express();
const PORT = 3001;

app.use(cors());
app.use(bodyParser.json());

// 模式数据库
const users = {
'user1': {
    id: 'user1',
    name: '张三',
    email: 'zhangsan@example.com',
    address: '北京市朝阳区',
    phone: '13800138000'
  },
  'user2': {
    id: 'user2',
    name: '李四',
    email: 'lisi@example.com',
    address: '上海市浦东新区',
    phone: '13900139000'
  },
}

// 模拟订单数据
const orders = {
 'user1': [
    {
      orderId: 'order1',
      userId: 'user1',
      products: [
        { id: 'p1', name: 'iPhone 13', price: 5999, quantity: 1 },
        { id: 'p2', name: 'AirPods Pro', price: 1299, quantity: 1 }
      ],
      total: 7298,
      status: '已发货',
      createTime: '2023-05-10T08:30:00Z'
    },
    {
      orderId: 'order2',
      userId: 'user1',
      products: [
        { id: 'p3', name: 'MacBook Pro', price: 12999, quantity: 1 }
      ],
      total: 12999,
      status: '已完成',
      createTime: '2023-04-15T10:15:00Z'
    }
  ],
  'user2': [
    {
      orderId: 'order3',
      userId: 'user2',
      products: [
        { id: 'p4', name: 'iPad Air', price: 4499, quantity: 1 },
        { id: 'p5', name: 'Apple Pencil', price: 999, quantity: 1 }
      ],
      total: 5498,
      status: '待付款',
      createTime: '2023-05-12T14:20:00Z'
    }
  ]
}

// 获取用户信息
app.get('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  const user = users[userId];

  if (user) {
    setTimeout(() => {
      res.json(user);
    }, Math.random() * 200 + 100); // 100-300毫秒的随机延迟
  } else {
    res.status(404).json({ error: 'User not found' });
  }
})

// 用户订单查下接口
app.get('/api/orders/:userId', (req, res) => {
  const userId = req.params.userId;

  if (!userId) {
    return res.status(400).json({ error: 'User ID is required' });
  }

  const userOrders = orders[userId] || [];
  setTimeout(() => {
    res.json(userOrders);
  }, Math.random() * 200 + 100); // 100-300毫秒的随机延迟
})

// 健康检测接口
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});


